<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<div>
				<el-select v-model="queryParams.projectCode" class="zs-select-md zs-space-right-sm" placeholder="项目" @change="changeProject" clearable filterable>
					<el-option v-for="item in projectList" :key="item.projectCode" :label="item.projectName" :value="item.projectCode" />
				</el-select>
				<el-select v-model="queryParams.communityId" collapse-tags collapse-tags-tooltip class="zs-select-md zs-space-right-sm" placeholder="区域" @change="changeArea" clearable filterable>
					<el-option v-for="item in areaList" :key="item.communityId" :label="item.communityName" :value="item.communityId" />
				</el-select>
				<el-select v-model="queryParams.buildId" class="zs-select-md zs-space-right-sm" placeholder="楼宇" @change="changeBuild" clearable filterable>
					<el-option v-for="item in buildList" :key="item.buildId" :label="item.buildName" :value="item.buildId" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.houseId || queryParams.startMonth || queryParams.endMonth || queryParams.tollItemName }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.houseId" class="zs-select-md zs-space-right-sm" placeholder="房间" @change="changeChargeItem" clearable filterable :teleported="false">
							<el-option v-for="item in roomList" :key="item.houseId" :label="item.simpleHouseNumber" :value="item.houseId" />
						</el-select>
						<el-date-picker class="zs-space-right-sm zs-space-right-sm" v-model="queryParams.startMonth" type="month" value-format="YYYY-MM" placeholder="权责开始月份" clearable :disabled-date="disabledDateStart" @change="queryList" :teleported="false" />
						<el-date-picker class="zs-space-right-sm zs-space-right-sm" v-model="queryParams.endMonth" type="month" value-format="YYYY-MM" placeholder="权责结束月份" clearable :disabled-date="disabledDateEnd" @change="queryList" :teleported="false" />
						<el-select v-model="queryParams.tollItemName" filterable class="zs-select-md zs-space-right-sm zs-space-top-sm" placeholder="收费项目" @change="queryList" clearable :teleported="false">
							<el-option v-for="item in toolItemList" :key="item.tollItemName" :label="item.tollItemName" :value="item.tollItemName" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</div>
			<div>
				<el-button class="zs-btn-plain zs-btn-md" @click="handleDownload">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
			</div>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main zs-table-first-row-special" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column label="序号" width="60" align="center">
					<template #default="scope">
						<span v-if="scope.$index == 0">合计</span>
						<span v-else>{{ scope.$index + (tableData.currentPage - 1) * curPageSize }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="communityname" label="区域" show-overflow-tooltip align="left" minWidth="120" :formatter="defaultTableData" />
				<el-table-column prop="buildname" label="楼宇" show-overflow-tooltip align="left" minWidth="100" :formatter="defaultTableData" />
				<el-table-column prop="simplehousenumber" label="房间号" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="cuname" label="客户" align="left" minWidth="120" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="tollitemname" label="收费项目" align="left" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="shouldamount" label="应收金额" align="right" minWidth="120" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="receivedamount" label="实收金额" align="right" minWidth="120" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="arrearsamount" label="欠款金额" align="right" minWidth="120" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="shouldtollmonth" label="权责月份" align="center" minWidth="120" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="arrearsAge" label="欠费账龄" align="center" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="enableStatusName" label="追缴时间" align="left" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="enableStatusName" label="追缴动作" align="left" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="enableStatusName" label="标准动作" align="left" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="enableStatusName" label="是否关联方" align="left" width="120" :formatter="defaultTableData" />
				<el-table-column prop="enableStatusName" label="是否诉讼" align="left" :formatter="defaultTableData" />
				<el-table-column prop="enableStatusName" label="责任人" align="left" :formatter="defaultTableData" />
				<el-table-column prop="preparerdate" label="发单日期" align="center" width="120" :formatter="defaultTableData" />
				<el-table-column prop="lspayment_date" label="最晚付款日" align="center" width="120" :formatter="defaultTableData" />
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { toThousands } from '@/utils/number-util';
	import { getProjectDropdownApi } from '@/api/SpecialReport/propertyReceivable';
	import { downloadNewFile, deepClone } from '@/utils/publicUtils';
	import detailApi from '@/api/Property/detailPages';

	const route = useRoute();
	const store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNum: 1, pageSize: curPageSize.value, communityId: route.query.communityId, buildId: route.query.buildId, houseId: route.query.houseId });

	// 列表数据源
	const queryList = async () => {
		tableData.loading = true;
        let params = deepClone(queryParams)
        params.startMonth = params.startMonth?.replace("-",'')
        params.endMonth = params.endMonth?.replace("-",'')
		let res = await detailApi.debtAnalyseRoomListApi(params);
		if (res.data.errorCode !== 200) return;
		tableData.data = res.data.data.list || [];
		if (res.data.data.list && res.data.data.list.length > 0) {
			tableData.data.unshift(res.data.data);
		}
		initData(tableData.data);
		tableData.total = res.data.totalCount || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
            let moneyFiledList = ['shouldamount', 'receivedamount', 'arrearsamount'];
            moneyFiledList.forEach(filed => {
                item[filed] = toThousands(item[filed]);
            })
		});
	};

	//切换项目
	const changeProject = () => {
		queryParams.communityId = '';
		queryParams.buildId = '';
		queryParams.houseId = '';
		queryParams.tollItemName = '';
		areaList.value = [];
		buildList.value = [];
		roomList.value = [];
		toolItemList.value = [];
		getAeraList();
		changeChargeItem();
	};

	//切换区域
	const changeArea = () => {
		queryParams.buildId = '';
		queryParams.houseId = '';
		buildList.value = [];
		roomList.value = [];
		getBuildList();
		changeChargeItem();
	};

	//切换楼宇
	const changeBuild = () => {
		queryParams.houseId = '';
		roomList.value = [];
		getRoomList();
		changeChargeItem();
	};

	//获取区域下拉列表
	const areaList = ref([]);
	const getAeraList = async () => {
		let res = await detailApi.getRegionDropdownDropdownApi({ projectCode: queryParams.projectCode });
		if (res.data.errorCode != 200) return;
		areaList.value = res.data.data;
	};

	//获取楼栋下拉列表
	const buildList = ref([]);
	const getBuildList = async () => {
		let res = await detailApi.getBuildDropdownApi({ projectCode: queryParams.projectCode });
		if (res.data.errorCode != 200) return;
		buildList.value = res.data.data;
	};

	//获取房间下拉列表
	const roomList = ref([]);
	const getRoomList = async () => {
		let res = await detailApi.getRoomDropdownApi({ projectCode: queryParams.projectCode, buildId: queryParams.buildId });
		if (res.data.errorCode != 200) return;
		roomList.value = res.data.data;
	};

	// 收费项目
	const toolItemList = ref([]);
	const getToolItemList = async () => {
		let res = await detailApi.getChargeItemDropdownApi(queryParams);
		if (res.data.errorCode != 200) return;
		toolItemList.value = res.data.data;
	};
    const changeChargeItem = () => {
        queryParams.tollItemName = '';
		toolItemList.value = [];
		getToolItemList();
    }

	//项目列表
	let projectList = ref([]);
	const getProjectList = async () => {
		let res = await getProjectDropdownApi({ projectCode: queryParams.projectCode });
		if (res.data.errorCode != 200) return;
		projectList.value = res.data.data;
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNum = size;
		}
		queryList();
	};

	// 导出
	const handleDownload = async () => {
		let params = deepClone(queryParams)
        params.startMonth = params.startMonth?.replace("-",'')
        params.endMonth = params.endMonth?.replace("-",'')
		const fileName = `欠款分析报表.xls`;
		let fileData = await detailApi.debtAnalyseRoomExportApi(params);
		downloadNewFile(fileData.data, fileName);
	};

	//时间判断
	const disabledDateStart = date => {
		if (!queryParams.endMonth) return false
		return date.getTime() > new Date(queryParams.endMonth).getTime();
	};

	const disabledDateEnd = date => {
		if (!queryParams.startMonth) return false
		return date.getTime() < new Date(queryParams.startMonth).getTime();
	};

	const defaultTableData = (row, column, cellValue, index) => {
		let emptyVal = index == 0 ? '' : '-';
		return cellValue || cellValue === 0 ? cellValue : emptyVal;
	};

	getProjectList();
	getAeraList();
	getBuildList();
	getRoomList();
	getToolItemList();
	queryList();
</script>
